import { useRuntimeConfig } from '#app'

export type Environment = 'local' | 'development' | 'production';

export interface ModuleConfig {
  baseURL: string;
  useMock: boolean;
}

// 是否启用mock数据，在构建时通过环境变量控制
const config = useRuntimeConfig();
const GLOBAL_ENABLE_MOCK = config.public.GLOBAL_ENABLE_MOCK === 'true';

export interface APIConfig {
  [module: string]: ModuleConfig;
}

export interface EnvironmentConfig {
  [env in Environment]: APIConfig;
}

declare module '#app' {
  interface NuxtApp {
    $apiConfig: {
      setEnvironment: (env: Environment) => void;
      getConfig: (module: string) => ModuleConfig;
      getCurrentEnvironment: () => Environment;
      GLOBAL_ENABLE_MOCK: boolean;
    }
  }
}

export const useApi = (moduleName: string) => {
  const nuxtApp = useNuxtApp();
  const config = nuxtApp.$apiConfig.getConfig(moduleName);
  console.log('API config', moduleName, config);
  // 强制禁用mock，直接连接后端API
  const useMock = false;

  // 动态导入mock函数
  const getMockFunction = async (method: string, url: string, customMockPath?: string) => {
    try {
      // 从URL中提取纯路径部分
      const urlObj = new URL(url, 'http://dummy.placeholder');
      const mockPath = customMockPath || `./mock/${urlObj.pathname}`;
      console.log(`Mock function will look for ${mockPath}`);
      // @ts-ignore
      const module = await import(/* @vite-ignore */mockPath);
      const FunctionName = `mock${method.charAt(0).toUpperCase() + method.slice(1)}`;
      return module[FunctionName];
    } catch (error) {
      console.warn(`Mock function not found for ${method} ${url}`);
      return null;
    }
  };

  return {
    get: async (url: string, options?: { mockPath?: string }) => {
      if (useMock) {
        const mockFn = await getMockFunction('get', url, options?.mockPath);
        if (mockFn) {
          const response = await mockFn(config);
          console.log('Mock response:', response);
          return response;
        }
      }
      
      const token = localStorage.getItem('userToken');
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };

      if (token) {
        headers.Authorization = `Bearer ${token}`;
      }

      const response = await globalThis.$fetch(url, {
        method: 'GET',
        baseURL: config.baseURL,
        credentials: 'include',
        headers
      });
      return response;
    },
    post: async (url: string, data: any) => {
      if (useMock) {
        const mockFn = await getMockFunction('post', url);
        if (mockFn) {
          const response = await mockFn(config, data);
          console.log('Mock response:', response);
          return response;
        }
      }

      const token = localStorage.getItem('userToken');
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };

      if (token) {
        headers.Authorization = `Bearer ${token}`;
      }

      const response = await globalThis.$fetch(url, {
        method: 'POST',
        body: data,
        baseURL: config.baseURL,
        credentials: 'include',
        headers
      });
      return response;
    },
    put: async (url: string, data: any) => {
      if (useMock) {
        const mockFn = await getMockFunction('put', url);
        if (mockFn) {
          const response = await mockFn(config, data);
          console.log('Mock response:', response);
          return response;
        }
      }

      const token = localStorage.getItem('userToken');
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };

      if (token) {
        headers.Authorization = `Bearer ${token}`;
      }

      const response = await globalThis.$fetch(url, {
        method: 'PUT',
        body: data,
        baseURL: config.baseURL,
        credentials: 'include',
        headers
      });
      return response;
    },
    delete: async (url: string) => {
      if (useMock) {
        const mockFn = await getMockFunction('delete', url);
        if (mockFn) {
          const response = await mockFn(config, data);
          console.log('Mock response:', response);
          return response;
        }
      }

      const token = localStorage.getItem('userToken');
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };

      if (token) {
        headers.Authorization = `Bearer ${token}`;
      }

      const response = await globalThis.$fetch(url, {
        method: 'DELETE',
        baseURL: config.baseURL,
        credentials: 'include',
        headers
      });
      return response;
    }
  };
};